<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

class AppServiceProvider extends ServiceProvider
{
    public function __construct($app)
    {
        parent::__construct($app);
        date_default_timezone_set('Asia/Shanghai');

    }
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        /*$this->app->bind(
           //TaobaoOrderRepository::class,

        );*/
        // 注册不区分大小写的服务别名
        /*$this->app->bind('ip2regionservice', function () {
            return new \App\Services\Ip2RegionService();
        });*/
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        if ((bool)env('SQL_LOG', true) == false) {
            return;
        }

        DB::listen(function ($sql) {
            $bindings = array_map(function ($binding) {
                if ($binding instanceof \DateTime) {
                    return $binding->format('\'Y-m-d H:i:s\'');
                }
                if (is_string($binding)) {
                    return "'$binding'";
                }
                return $binding;
            }, $sql->bindings);

            $query = $sql->sql;
            
            if (!empty($bindings)) {
                $query = str_replace(['%', '?'], ['%%', '%s'], $query);
                $query = vsprintf($query, $bindings);
            }

            $logEntry = '[' . date('Y-m-d H:i:s') . '] ' . $query . ';' . PHP_EOL;
            
            file_put_contents(
                storage_path('logs/query-' . date('Y-m-d') . '.log'),
                $logEntry,
                FILE_APPEND | LOCK_EX
            );
        });
       
    }

}
